/*
Estimate the child penalty to wage earnings for non-entrepreneur
Norwegian mothers.
*/

* start with panel of all Norwegian adults
cd "$root"
do "$root/code/admin/ado/exportmat.ado"

global figpath $root/estimates/admin/wage_penalty

use data/admin/raw/ee_extended_9518.dta, clear
collapse (sum) k_lonn, by(lnr year)
tempfile total_wage
save `total_wage'

use data/admin/raw/living_64_20.dta, clear
keep if inrange(year, 1995, 2018)

merge m:1 lnr using data/admin/raw/constant_traits.dta, keep(3) nogen
keep if male == 0
gen age = year - b_year

merge m:1 lnr using data/admin/intermediate/first_births_to_2019.dta, keep(1 3) nogen
gen age_first_birth = year_first_child - b_year
keep if inrange(age_first_birth, 20, 45) // Kleven et al. do this
keep if inrange(year_first_child, 2001, 2018)

* exclude entrepreneurs
preserve
use data/admin/raw/firm_ownership_01_19.dta, clear
keep if inlist(owner_cat, 1, 2, 3)
keep lnr
duplicates drop
tempfile entrepreneurs
save `entrepreneurs'
restore

merge m:1 lnr using `entrepreneurs', keep(1) nogen

* merge on wages
merge 1:1 lnr year using `total_wage', keep(1 3) nogen
replace k_lonn = 0 if k_lonn == .

merge m:1 year using data/admin/raw/cpi_1960_2020_USD.dta, nogen
drop if lnr == .
replace k_lonn = k_lonn / (cpi * 1.0612) // 2011 to 2015 USD

* generate event time dummies
gen event_time = year - year_first_child
keep if inrange(event_time, -5, 10)
gen et = event_time + 6

quietly {
    tab age, gen(dage)
    tab year, gen(dyear)
    tab et, gen(det)
}
drop det4 // event time -2
drop dage1 dyear1 // collinearity
	
reg k_lonn dage* dyear* det*, vce(cluster lnr) nocons
cap drop flag_sample
gen flag_sample = e(sample)
*estimates store fem_reg

* get percentages to rescale estimates
local es_orig
local es_lincom_y0
local es_rs
unab itervars : dage* dyear*

foreach et of numlist 1/3 5/16 {
    local es_orig "`es_orig' (det`et' = det`et')"
    * get E[~Y | t] = \sum \beta_{x} * P[X = x | t]
    local y0_sum "(y0_`et' = 0 "
    foreach x of local itervars {
      qui: sum `x' if det`et' == 1 & flag_sample == 1
      local y0_sum "`y0_sum' + `r(mean)' * `x'"
    }
    local es_lincom_y0 "`es_lincom_y0' `y0_sum')"
    local es_rs "`es_rs' (et_`et' = det`et' / y0_`et')"
}

xlincom `es_lincom_y0' `es_orig', post

local es_rs
foreach et of numlist 1/3 5/16 {
      local es_rs "`es_rs' (et_`et' : _b[det`et'] / _b[y0_`et'])"
}

nlcom `es_rs', post
exportmat r(table), filename("wage_penalty_male0.csv") path("$figpath")

* get averages
local es_avg "avg_10 = (0"
foreach et of numlist 7/16 {
    local es_avg "`es_avg' + et_`et'"
}
local es_avg "`es_avg') / 10"
xlincom `es_avg', post
exportmat r(table), filename("wage_penalty_male0_agg.csv") path("$figpath")


